package com.hui.controller;


import com.hui.config.FindFile;
import com.hui.config.JsonData;
import com.hui.config.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.hui.controller
 * @Author: HUI
 * @CreateTime: 2021-12-07 09:28
 * @Description:
 */

//文件上传
@RestController
@RequestMapping("/files")
@Slf4j
public class FileUploadController {

    @Value("${server.port}")//拿到配置文件的的属性
    private String port;

    private static final String ip = "http://localhost";


    //文件上传
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) {
        //使用UUID解决文件重名问题
        String filename = file.getOriginalFilename();//获取源文件名称
        //获得当前项目的路径，与 resources目录进行拼接
        String rootPathName = System.getProperty("user.dir") + "/src/main/resources/files";
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String localFileName = rootPathName + "\\" + uuid + "-" + filename;
        try {
            file.transferTo(new File(localFileName));//filename放在最后面，因为有后缀名
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("-1", "文件上传失败！");
        }

        //返回下载接口
        return Result.success(ip + ":" + port + "/files/download/" + filename);
    }


    //富文本文件上传（自己写的返回格式，注意前端传过来的文件名是否和后端文件名一致）
    @PostMapping("/uploadDetail")
    public Map<String,Object> uploadDetail(MultipartFile  file,HttpServletResponse response) {
        //使用UUID解决文件重名问题
        String filename = file.getOriginalFilename();//获取源文件名称
        //获得当前项目的路径，与 resources目录进行拼接
        String rootPathName = System.getProperty("user.dir") + "/src/main/resources/files";
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String localFileName = rootPathName + "\\" + uuid + "-" + filename;
        try {
            file.transferTo(new File(localFileName));//filename放在最后面，因为有后缀名
        } catch (IOException e) {
            e.printStackTrace();
//            return Result.error("-1", "文件上传失败！");
        }



        //设置响应格式
        response.setContentType("application/json");

        String url = ip + ":" + port + "/files/download/" + filename;
        Map<String, Object> jsonMap = new HashMap<>();
        JsonData jsonData = new JsonData();
        jsonData.setUrl(url);
        Object[] objects = {jsonData};
        jsonMap.put("data",objects);
        jsonMap.put("errno", 0);


        //返回下载接口
        return jsonMap;
    }


    //文件下载
    @GetMapping("download/{flag}")
    public void download(@PathVariable(name = "flag") String flag, HttpServletResponse response) {
        BufferedInputStream bs;//缓冲流对象
        FileInputStream fs;//输入流对象
        OutputStream os;  // 新建一个输出流对象
        String fileName = FindFile.findFile(flag);//获得文件路径


        if (!fileName.isBlank()) {

            try {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");

                fs = new FileInputStream(fileName);//通过文件的路径读取文件字节流
                bs = new BufferedInputStream(fs);//存入缓存流

                os = response.getOutputStream();// 通过输出流返回文件

                os.write(bs.readAllBytes());


                os.flush();
                os.close();
                fs.close();
                bs.close();


            } catch (FileNotFoundException e) {
                log.info("读取字节流时发生错误！");
                e.printStackTrace();

            } catch (IOException e) {
                log.info("写入缓冲流时发生错误！");
                e.printStackTrace();

            }


        } else {
            log.info("没有该文件！");
        }


    }

}
